// 管理员
const experss = require("express")
const {
    asyncHandler
} = require("../getSendResult")
const {
    upload
} = require("../../services/CurrServ")
const router = experss.Router()
const {
    public
} = require("../jwt")
const path = require("path")
const fs = require("fs")
const {
    login,
    Info,
    evaluate,
    students,
    updataLoginPwd,
    getup,
    destination,
    clean,
    updateAvatar,
    putService
} = require("../../services/adminServ")
const multer = require("multer");
const init = require("../../util/init")
// 权限判定
const checkPermission = require("../checkPermission")

router.all("*", (req, res, next) => {
    checkPermission(req, res, next, [0, 1])
})

/**
 * 登录
 */
router.post("/login", asyncHandler(async (req, res) => {
    const result = await login({
        adminId: req.body.adminId,
        loginPwd: req.body.loginPwd
    })
    if (result.code === 401) {
        return result
    }
    if (result.state === 2) {
        return result
    } else {
        const Info = {
            id: result.token.id,
            adminId: result.token.adminId,
            authentication: result.token.authentication
        }
        const token = public(res, undefined, Info)
        return {
            state: 1,
            token,
            authentication: result.token.authentication
        }
    }

}))
/**
 * 获取管理员的个人信息
 */
router.get("/Info", asyncHandler(async (req, res) => {

    const reslut = await Info(req.user.id)
    return reslut
}))

/**
 * 发布宿舍评价
 */
router.post("/evaluate", asyncHandler(async (req, res) => {
    const resluts = await init.sequelize.transaction(async t => {
        const reslut = await evaluate({
            fraction: +req.body.fraction,
            comment: req.body.comment,
            roomNoId: +req.body.roomNoId,
            id: req.user.id
        })
        return reslut
    })
    return resluts
}))


/**
 * 获取学生信息
 */
router.get("/students", asyncHandler(async (req, res) => {
    const resluts = await init.sequelize.transaction(async t => {
        const keyword = {
            dormitoryId: +req.query.keyword.dormitoryId || null,
            floorId: +req.query.keyword.floorId || null,
            roomNoId: +req.query.keyword.roomNoId || null,
            loginId: req.query.keyword.loginId || null,
            nickname: req.query.keyword.nickname || null,

        }
        const reslut = await students(+req.query.page || 1, +req.query.limit || 10, +req.user.id, keyword)
        return reslut
    })
    return resluts

}))

/**
 * 获取起床记录
 */
router.get("/getup", asyncHandler(async (req, res) => {
    const conditionObj = {
        studentId: +req.query.studentId || null,
        startingTime: req.query.startingTime || null,
        endTime: req.query.endTime || null
    };
    const reslut = await getup(+req.query.page || 1, +req.query.limit || 10, conditionObj)
    return reslut
}))

/**
 * 获取归宿记录
 */
router.get("/destination", asyncHandler(async (req, res) => {
    const conditionObj = {
        studentId: +req.query.studentId || null,
        startingTime: req.query.startingTime || null,
        endTime: req.query.endTime || null
    };
    const reslut = await destination(+req.query.page || 1, +req.query.limit || 10, conditionObj)
    return reslut
}))

/**
 * 获取打扫记录
 */
router.get("/clean", asyncHandler(async (req, res) => {
    const conditionObj = {
        studentId: +req.query.studentId || null,
        startingTime: req.query.startingTime || null,
        endTime: req.query.endTime || null
    };
    const reslut = await clean(+req.query.page || 1, +req.query.limit || 10, conditionObj);
    return reslut
}))

/**
 *  修改密码
 */
router.put("/updataLoginPwd", asyncHandler(async (req, res) => {
    const resluts = await init.sequelize.transaction(async t => {
        const reslut = await updataLoginPwd({
            id: req.user.id,
            oldPwd: req.body.oldPwd,
            newPwd: req.body.newPwd,
            confirmPwd: req.body.confirmPwd
        })

        return reslut
    })
    return resluts
}))
/**
 * 修改头像
 */
router.put("/updateAvatar", multer().single("newAvatar"), asyncHandler(async (req, res) => {
    const resluts = await init.sequelize.transaction(async t => {
        const reslut = await upload(req.file, async function (filename) {
            const body = {
                ...req.body,
                avatar: filename ? `/upload/${filename}` : null
            }
            try {
                const res = await updateAvatar({
                    id: req.user.id,
                    avatar: body.avatar,
                })
                return res
            } catch (err) {
                return {
                    code: 401,
                    err
                }
            }
        })
        // 删除不需要头像
        if (req.body.oldAvatar && !process.env.DEFAULTAVATAR.includes(req.body.oldAvatar)) {
            fs.unlink(path.resolve(__dirname, "../../public") + req.body.oldAvatar, (err) => {
                if (err) {
                    return err
                }
            })
        }
        return reslut
    })
    return resluts
}))

router.put("/putService", multer().single("avatar"), asyncHandler(async (req, res) => {
    const resluts = await init.sequelize.transaction(async t => {
        const reslut = await upload(req.file, async function (filename) {
            const body = {
                ...req.body,
                avatar: filename ? `/upload/${filename}` : null
            }
            const res = await putService({
                id: +body.id,
                RepairEndImg: body.avatar,
                ResponsiblePerson: req.user.adminId
            })
            return res
        })
        return reslut
    })
    return resluts
}))

module.exports = router